<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true" label-width="94px">
        <el-form-item label="项目">
          <el-select
            v-model="searchParam.projectId"
            placeholder="请选择项目"
            clearable
            filterable
            @change="projectChange"
          >
            <el-option
              v-for="item in projectList"
              :key="item.id"
              :label="item.projectCode"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工序">
          <el-select
            v-model="searchParam.processId"
            placeholder="请选择工序"
            clearable
            :disabled="!searchParam.projectId"
            filterable
            @change="processChange"
          >
            <el-option
              v-for="item in processList"
              :key="item.id"
              :label="item.processCode"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设备">
          <el-select
            v-model="searchParam.equipId"
            placeholder="请选择设备"
            clearable
            filterable
            :disabled="!searchParam.processId"
            @change="equipChange"
          >
            <el-option
              v-for="item in equipList"
              :key="item.id"
              :label="item.equipCode"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <span v-show="!collapsed">
          <el-form-item label="产品型号">
            <el-select
              v-model="searchParam.productId"
              placeholder="请选择产品型号"
              clearable
              filterable
              @change="productChange"
            >
              <el-option
                v-for="item in productList"
                :key="item.id"
                :label="item.productCode"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="检具类型">
            <el-select
              v-model="searchParam.gageEquipToolKind"
              placeholder="请选择量检具类型"
              clearable
              @change="toolKindChange"
            >
              <el-option
                v-for="item in useDictionary('InspectionToolKind')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="检具设备">
            <el-select
              v-model="searchParam.gageEquipCode"
              placeholder="请选择检具设备"
              clearable
              filterable
              :disabled="!searchParam.gageEquipToolKind"
            >
              <el-option
                v-for="item in gageEquipList"
                :key="item.toolCode"
                :label="item.toolCode"
                :value="item.toolCode"
              />
            </el-select>
          </el-form-item>
          <!--          <el-form-item label="检具设备号">-->
          <!--            <el-input-->
          <!--              v-model="searchParam.gageEquipMarkCode"-->
          <!--              placeholder="请输入检具设备号"-->
          <!--              clearable-->
          <!--              @keyup.enter="search"-->
          <!--            />-->
          <!--          </el-form-item>-->
          <el-form-item label="特性项">
            <el-select
              v-model="searchParam.specificId"
              placeholder="请选择特性项"
              clearable
              filterable
              :disabled="!canSelectSpecific"
              @change="specificChange"
            >
              <el-option
                v-for="item in specificList"
                :key="item.paramId"
                :label="item.paramName"
                :value="item.paramId"
              />
            </el-select>
          </el-form-item>
          <!--          <el-form-item label="过程能力类型">-->
          <!--            <el-select-->
          <!--              v-model="searchParam.graphClassify"-->
          <!--              placeholder="请选择过程能力类型"-->
          <!--              clearable-->
          <!--            >-->
          <!--              <el-option-->
          <!--                v-for="item in useDictionary('AbilityType')"-->
          <!--                :key="item.value"-->
          <!--                :label="item.label"-->
          <!--                :value="item.value"-->
          <!--              />-->
          <!--            </el-select>-->
          <!--          </el-form-item>-->
          <el-form-item label="是否参与计算">
            <el-select
              v-model="searchParam.status"
              placeholder="请选择是否参与计算"
              clearable
            >
              <el-option label="是" value="1" />
              <el-option label="否" value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="searchParam.pointTimeSearch"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              @change="getPointTime"
            />
          </el-form-item>
        </span>
        <el-form-item>
          <el-button type="primary" @click="search">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="reset">
            <i-ep-refresh />
            重置
          </el-button>
          <el-button type="primary" link @click="collapsed = !collapsed">
            {{ collapsed ? "展开" : "收起" }}
            <i-ep-arrowUp v-if="!collapsed" class="ml-[3px]" />
            <i-ep-arrowDown v-else class="ml-[3px]" />
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        :cell-style="{ 'text-align': 'center' }"
      >
        <el-table-column
          label="工序"
          prop="processCode"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          label="设备"
          prop="equipCode"
          min-width="180"
          show-overflow-tooltip
        />
        <el-table-column
          label="项目"
          prop="projectCode"
          min-width="180"
          show-overflow-tooltip
        />
        <el-table-column
          label="产品型号"
          prop="modelCode"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          label="检具设备"
          prop="gageEquipMarkCode"
          min-width="150"
          show-overflow-tooltip
        />
        <!--        <el-table-column-->
        <!--          label="检具设备号"-->
        <!--          prop="gageEquipMarkCode"-->
        <!--          min-width="180"-->
        <!--          show-overflow-tooltip-->
        <!--        />-->
        <el-table-column
          label="特性项"
          prop="specificCode"
          min-width="220"
          show-overflow-tooltip
        />
        <el-table-column
          label="公差上限"
          prop="upperLimitValue"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="公差下限"
          prop="lowerLimitValue"
          min-width="100"
          show-overflow-tooltip
        />
        <!-- 百检/抽检(待衔接) -->
        <!-- <el-table-column
          label="百检/抽检(待衔接)"
          prop="checkType"
          min-width="150"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{ scope.row.checkType }}
          </template>
        </el-table-column> -->
        <!--        <el-table-column-->
        <!--          label="过程能力类型"-->
        <!--          prop="graphClassify"-->
        <!--          min-width="180"-->
        <!--          show-overflow-tooltip-->
        <!--        >-->
        <!--          <template #default="scope">-->
        <!--            {{ useDictionary("AbilityType", scope.row.graphClassify) }}-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column
          label="特性值"
          prop="paramValue"
          min-width="110"
          show-overflow-tooltip
        >
          <template #default="scope">
            <span
              :class="
                sizeColorHandle(
                  scope.row.paramValue,
                  scope.row.lowerLimitValue,
                  scope.row.upperLimitValue
                )
              "
              >{{ scope.row.paramValue }}</span
            >
          </template>
        </el-table-column>
        <el-table-column
          label="特性值创建时间"
          prop="detectionTime"
          min-width="180"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{ scope.row.detectionTime }}
          </template>
        </el-table-column>
        <el-table-column
          label="工位"
          prop="location"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="操作时间"
          prop="updateTime"
          min-width="180"
          show-overflow-tooltip
        />
        <el-table-column
          label="参与计算"
          prop="status"
          min-width="85"
          fixed="right"
          show-overflow-tooltip
        >
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.status == 1">是</el-tag>
            <el-tag type="info" v-if="scope.row.status == 2">否</el-tag>
            <span v-else></span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="150">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              v-if="scope.row.status == 1"
              @click="openConfirm(scope.row)"
            >
              移除
            </el-button>
            <el-button
              v-if="scope.row.status == 2"
              type="primary"
              size="small"
              link
              @click="openConfirm(scope.row)"
            >
              取消移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { useTable, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import {
  getMdmproductinfosApi,
  getMdmprojectinfosApi,
  getMdminspectiontoolApi,
  getSpecificListApi,
  getMdmProcessEquipApi,
  getMdmProcessProjectApi,
} from "@/utils/commonData";
import { sizeColorHandle } from "@/utils/commonHooks";
defineOptions({
  name: "QMSPCMPCMMONITORINGITEM",
  inheritAttrs: false,
});

/**
 * 工序列表获取的条件：项目不为空
 * 设备列表获取的条件：项目、工序不为空
 * 产品型号列表：无条件
 * 检具设备列表获取的条件：检具类型不为空
 * 特性值列表获取的条件：工序、设备、产品、检具不为空
 **/

// 搜索项折叠
const collapsed = ref(false);

// 请求参数
const requestApi = "/dmpDosPcm/pcmtimingpoint/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  // 项目
  projectCode: "",
  projectId: "",
  // 工序
  processCode: "",
  processId: "",
  // 设备
  equipCode: "",
  equipId: "",
  // 产品型号
  productCode: "",
  productId: "",
  // 检具类型
  gageEquipToolKind: "",
  // 检具名称
  gageEquipCode: "",
  // 机器号
  gageEquipMarkCode: "",
  // 特性
  specificId: "",
  specificCode: "",
  // 过程能力类型
  graphClassify: "",
  // 是否参与计算
  status: "",
  // 创建时间
  pointTimeStart: "",
  pointTimeEnd: "",
  pointTimeSearch: [],
};

const deleteParam = {
  api: "/eam/equPrecisionCheckPlan/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {
  setTimeout(function () {}, 10);
}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

/** ----------搜索联动开始------------ **/

onMounted(() => {
  // 获取table列表
  getTableList();
  // 获取项目列表
  getProjectList();
  // 获取产品型号列表
  getProductList();
});

// 通过工序查询设备列表
const equipList = ref(<any>[]);
async function getEquipList(id: string) {
  equipList.value = (await getMdmProcessEquipApi({ processId: id })) || [];
}
function equipChange(id: string) {
  if (id) {
    const current: any =
      equipList.value?.filter((e: any) => e.id === id)[0] ?? {};
    searchParam.value.equipCode = current.equipCode || "";
  } else {
    searchParam.value.equipCode = "";
  }
}

// 获取工序列表
const processList = ref<any>([]);
async function getProcessList(id: string) {
  processList.value = (await getMdmProcessProjectApi({ projectId: id })) || [];
}
function processChange(id: string) {
  searchParam.value.equipId = "";
  searchParam.value.equipCode = "";
  if (id) {
    const current: any =
      processList.value?.filter((e: any) => e.id === id)[0] ?? {};
    searchParam.value.processCode = current.processCode || "";
    getEquipList(id);
  } else {
    searchParam.value.processCode = "";
    equipList.value = [];
  }
}

// 获取项目列表
const projectList = ref<any>([]);
async function getProjectList() {
  projectList.value = (await getMdmprojectinfosApi({})) || [];
}
function projectChange(id: string) {
  searchParam.value.equipId = "";
  searchParam.value.equipCode = "";
  searchParam.value.processId = "";
  searchParam.value.processCode = "";
  if (id) {
    const current: any =
      projectList.value?.filter((e: any) => e.id === id)[0] ?? {};
    searchParam.value.projectCode = current.projectCode || "";
    getProcessList(id);
  } else {
    searchParam.value.projectCode = "";
    equipList.value = [];
    processList.value = [];
  }
}

// 获取产品型号列表
const productList = ref<any>([]);
async function getProductList() {
  productList.value = (await getMdmproductinfosApi({})) || [];
}
function productChange(id: string) {
  if (id) {
    const current: any =
      productList.value?.filter((e: any) => e.id === id)[0] ?? {};
    searchParam.value.productCode = current.productCode || "";
  } else {
    searchParam.value.productCode = "";
  }
}

// 量检具类型变化
function toolKindChange(type: string) {
  searchParam.value.gageEquipCode = "";
  searchParam.value.gageEquipMarkCode = "";
  if (type) {
    getGageEquipList(type);
  } else {
    gageEquipList.value = [];
  }
}

// 特性值变化
function specificChange(id: string) {
  if (id) {
    const current: any =
      specificList.value?.filter((e: any) => e.paramId === id)[0] ?? {};
    searchParam.value.specificCode = current.paramCode || "";
  } else {
    searchParam.value.specificCode = "";
  }
}

// 获取量检具列表
const gageEquipList = ref<any>([]);
async function getGageEquipList(type: string) {
  gageEquipList.value =
    (await getMdminspectiontoolApi({ toolKind: type })) || [];
}

// 获取特性值列表
const specificList = ref<any>([]);
async function getSpecificList() {
  specificList.value =
    (await getSpecificListApi({
      equipId: searchParam.value.equipId,
      gageEquipMarkCode: searchParam.value.gageEquipCode,
      modelId: searchParam.value.productId,
      processId: searchParam.value.processId,
    })) || [];
}

// 检测必填项，筛选特性值列表
const canSelectSpecific = ref(false);
watch(
  () => searchParam.value,
  (newVal) => {
    if (
      newVal.equipCode &&
      newVal.gageEquipCode &&
      newVal.productCode &&
      newVal.processCode
    ) {
      canSelectSpecific.value = true;
      getSpecificList();
    } else {
      canSelectSpecific.value = false;
    }
  },
  {
    deep: true,
  }
);

/** ----------搜索联动结束------------ **/

// 更新创建时间
function getPointTime(data: any) {
  if (data) {
    searchParam.value.pointTimeStart = data[0];
    searchParam.value.pointTimeEnd = data[1];
  } else {
    searchParam.value.pointTimeStart = "";
    searchParam.value.pointTimeEnd = "";
  }
}

// 计算状态更改操作
const openConfirm = (row: any) => {
  ElMessageBox.confirm(
    row.status == 1
      ? `移除后，该监控项将不参与计算，是否继续？`
      : `取消移除后，该监控项将参与计算，是否继续？`,
    "提示",
    {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(async () => {
      await request({
        url: "/dmpDosPcm/pcmtimingpoint/update",
        method: "post",
        data: {
          id: row.id,
          specificCode: searchParam.value.specificCode,
          status: row.status == 1 ? 2 : 1,
        },
      }).then(() => {
        ElMessage.success("操作成功");
        search();
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消",
      });
    });
};
</script>
<style>
.red {
  color: #f56c6c;
}
</style>
